import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    debugShowCheckedModeBanner: false,
    home: PageViewPage(),
  ));
}

class PageViewPage extends StatefulWidget {
  const PageViewPage({super.key});

  @override
  State<PageViewPage> createState() => _PageViewPageState();
}

class _PageViewPageState extends State<PageViewPage> {
  final List<Widget> _list = [];
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 10; i++) {
      _list.add(MyPage(text: "$i页"));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Page View Demo"),
      ),
      body: PageView(
        scrollDirection: Axis.horizontal,
        onPageChanged: (index) {
          if (index + 2 == _list.length) {
            setState(() {
              for (var i = 0; i < 10; i++) {
                _list.add(MyPage(text: "${i + _list.length}页"));
              }
            });
          }
        },
        children: _list,
      ),
    );
  }
}

class MyPage extends StatefulWidget {
  final String text;
  const MyPage({super.key, required this.text});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        "第：${widget.text}",
        style: Theme.of(context).textTheme.headlineMedium,
      ),
    );
  }
}
